package com.gitee.loyo;

import io.vertx.core.Future;
import io.vertx.core.http.HttpServerRequest;
import io.vertx.core.http.HttpServerResponse;

import java.nio.charset.StandardCharsets;
import java.util.Base64;

public class Auth {

    public static void needBasicAuth(HttpServerResponse response){
        response.putHeader("WWW-Authenticate", "Basic realm=\"Secure Area\"")
            .setStatusCode(401)
            .end();
    }

    public static boolean checkBasicAuthToken(HttpServerRequest request){
        String authorization = request.getHeader("Authorization");
        if(authorization == null || authorization.isEmpty() || !authorization.startsWith("Basic "))
            return false;

        try{
            String token = authorization.substring("Basic ".length());
            String[] usernameWithPassword = new String(Base64.getDecoder().decode(token), StandardCharsets.UTF_8).split("\\:", 2);
            return usernameWithPassword[0].equals(BridgeConfig.INSTANCE.basicAuthUsername)
                && usernameWithPassword[1].equals(BridgeConfig.INSTANCE.basicAuthPassword);
        }catch (Exception e){
            return false;
        }
    }

    public static boolean basicAuthEnabled() {
        return BridgeConfig.INSTANCE.basicAuthEnabled;
    }

    public static Future<Void> save(Boolean basicAuthEnabled, String username, String password) {
        BridgeConfig.INSTANCE.basicAuthEnabled = Boolean.TRUE.equals(basicAuthEnabled);
        BridgeConfig.INSTANCE.basicAuthUsername = username;
        BridgeConfig.INSTANCE.basicAuthPassword = password;

        return BridgeConfig.INSTANCE.save();
    }
}
